<template>
  <el-dialog
    title="添加虚拟成员"
    :visible.sync="value"
    width="40%"
    :before-close="()=>{ resetForm('ruleForm') }"
  >
    <el-form ref="ruleForm" :model="ruleForm" :rules="rules" label-width="100px">
      <el-form-item label="头像" prop="avatar">
        <el-upload
          class="uploadImg"
          :action="UPLOAD_URL"
          list-type="picture-card"
          name="image"
          :limit="1"
          :file-list="imgFileList"
          :on-success="handleSuccess"
          :on-remove="handleRemove"
        >
          <i class="el-icon-plus" />
        </el-upload>
      </el-form-item>

      <el-form-item label="昵称" prop="nickname">
        <el-input v-model="ruleForm.nickname" />
      </el-form-item>
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button @click="resetForm('ruleForm')">取 消</el-button>
      <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
    </span>
  </el-dialog>
</template>

<script>
import { UPLOAD_URL } from '@/env'
export default {
  props: {
    pubVue: {
      type: Object,
      default: () => {
        return {}
      }
    },
    value: {
      type: Boolean,
      default: false
    },
    groupId: {
      type: String,
      default: ''
    }
  },
  data() {
    return {
      imgFileList: [], // 主图回显
      UPLOAD_URL,
      ruleForm: {
        nickname: '',
        avatar: ''
      },
      rules: {
        nickname: [
          { required: true, message: '请输入昵称', trigger: 'blur' }
        ],
        avatar: [
          { required: true, message: '请上传头像', trigger: 'blur' }
        ]
      }
    }
  },
  methods: {
    handleSuccess(res) {
      if (res.code == 200) {
        this.ruleForm.avatar = res.data.path
      } else {
        this.$message.error(res.msg)
      }
    },
    handleRemove() {
      this.imgFileList = []
      this.ruleForm = {}
    },

    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          this.$request.post('/admin/group/robot/save', {
            group_id: this.groupId,
            ...this.ruleForm
          }).then(res => {
            this.$refs[formName].clearValidate()
            this.imgFileList = []
            this.ruleForm = {}
            this.$emit('input', false)
            this.pubVue.$emit('refresh')
          }).catch()
        }
      })
    },
    resetForm(formName) {
      this.$refs[formName].clearValidate()
      this.imgFileList = []
      this.ruleForm = {}
      this.$emit('input', false)
    }
  }
}
</script>

<style lang="scss" scoped>
    .uploadImg ::v-deep .el-upload--picture-card{
      height:100px;
      width:100px;
      line-height: 104px;
    }
    .uploadImg ::v-deep .el-upload-list--picture-card .el-upload-list__item{
      height:100px;
      width:100px;
      line-height: 104px;
    }
    .uploadImg ::v-deep .el-icon-upload-success{
      position: absolute;
      right: 15px;
      top: 0px;
    }
</style>
